package nachos.threads;

import nachos.machine.*;
import java.util.Random;


/**
 * A Tester for the Alarm class
 *
 * Creates two threads, one that prints an output every 1000 cycles, the other every 37 cycles to 
 * show that the Alarm is able to force context switches between the two threads with the timer.
 */
public class AlarmTest {

    public static void runTest() {
	    System.out.println("**** Alarm testing begins ****");
      
      AlarmTestOne alarmOne = new AlarmTestOne();
      KThread alarmOneThread = new KThread( alarmOne);
      alarmOneThread.setName( "AlarmOneThread" );
      alarmOneThread.fork();
      
      AlarmTestTwo alarmTwo = new AlarmTestTwo();
      KThread alarmTwoThread = new KThread( alarmTwo);
      alarmTwoThread.setName( "AlarmTwoThread" );
      alarmTwoThread.fork();
      
      alarmOneThread.join();
      alarmTwoThread.join();

    	System.out.println("**** Alarm testing end ****");
      KThread.yield();
    }

    private static class AlarmTestOne implements Runnable {
        public void run() {
          for (int i = 0; i < 1000; i++) {
            if(i % 100 == 0) {
              System.out.println( "1: " + i );
              ThreadedKernel.alarm.waitUntil(1000);
            }
          }
        }
    }
    private static class AlarmTestTwo implements Runnable {
        public void run() {
          for (int i = 0; i < 1000; i++) {
            if(i % 100 == 0) {
              System.out.println( "2: " + i );
              ThreadedKernel.alarm.waitUntil(37);
            }
          }
        }
    }
}
